from turtle import st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime, timedelta

# 特然
# 设置中文字体
plt.rcParams["font.family"] = ["SimHei", "WenQuanYi Micro Hei", "Heiti TC"]
plt.rcParams["axes.unicode_minus"] = False  # 解决负号显示问题

# 页面设置
st.set_page_config(
    page_title="人寿保险业务看板",
    page_icon="📊",
    layout="wide",
    initial_sidebar_state="expanded"
)

# 标题
st.title("人寿保险业务看板")

# 侧边栏 - 筛选器
with st.sidebar:
    st.header("筛选条件")

    # 时间范围选择
    start_date = st.date_input(
        "开始日期",
        datetime.now() - timedelta(days=365)
    )
    end_date = st.date_input(
        "结束日期",
        datetime.now()
    )

    # 业务类型选择
    business_types = ["个人寿险", "团体寿险", "健康险", "意外险", "全部"]
    selected_business = st.selectbox("业务类型", business_types)

    # 区域选择
    regions = ["华东", "华北", "华南", "西南", "西北", "东北", "全部"]
    selected_region = st.selectbox("区域", regions)

    # 刷新数据按钮
    if st.button("刷新数据"):
        st.session_state.data_updated = True


# 模拟数据生成
@st.cache_data
def generate_insurance_data():
    # 设置随机种子以确保结果可重现
    np.random.seed(42)

    # 生成时间序列 (过去12个月)
    dates = pd.date_range(end=datetime.now(), periods=12, freq='MS')

    # 生成基础数据
    data = {
        'date': dates,
        'premium_income': np.random.randint(1000000, 5000000, 12),  # 保费收入
        'reinsurance_premium': np.random.randint(300000, 1500000, 12),  # 分保费收入
        'net_premium': np.random.randint(700000, 3500000, 12),  # 自留保费
        'first_year_premium': np.random.randint(200000, 1000000, 12),  # 首年保费
        'standard_premium': np.random.randint(800000, 3800000, 12),  # 标准保费
        'num_agents': np.random.randint(500, 1000, 12),  # 代理人数量
        'net_assets': np.random.randint(5000000, 15000000, 12),  # 净资产
        'market_share': np.random.uniform(5, 15, 12),  # 市场份额(%)
        'incremental_market_share': np.random.uniform(3, 10, 12)  # 增量市场份额(%)
    }

    df = pd.DataFrame(data)

    # 计算衍生指标
    # 分保费收入增长率
    df['reinsurance_growth_rate'] = df['reinsurance_premium'].pct_change() * 100
    # 自留保费增长率
    df['net_premium_growth_rate'] = df['net_premium'].pct_change() * 100
    # 首年保费与保费收入比
    df['first_year_premium_ratio'] = df['first_year_premium'] / df['premium_income']
    # 标准保费增长率
    df['standard_premium_growth_rate'] = df['standard_premium'].pct_change() * 100
    # 人均保费
    df['premium_per_agent'] = df['premium_income'] / df['num_agents']
    # 自留保费占净资产比
    df['net_premium_to_assets_ratio'] = df['net_premium'] / df['net_assets'] * 100

    # 添加一些季节性波动
    seasonal_factors = [1.1, 1.2, 0.9, 0.8, 1.0, 1.3, 1.2, 1.0, 0.9, 1.1, 1.3, 1.2]
    for i, factor in enumerate(seasonal_factors):
        df.loc[i, 'premium_income'] *= factor
        df.loc[i, 'reinsurance_premium'] *= factor
        df.loc[i, 'net_premium'] *= factor

    # 确保增长率在合理范围
    df['reinsurance_growth_rate'] = df['reinsurance_growth_rate'].clip(-30, 50)
    df['net_premium_growth_rate'] = df['net_premium_growth_rate'].clip(-20, 40)
    df['standard_premium_growth_rate'] = df['standard_premium_growth_rate'].clip(-25, 45)

    return df


# 加载数据
df = generate_insurance_data()

# 显示最新数据概览
latest_data = df.iloc[-1].copy()
previous_data = df.iloc[-2].copy()

# 格式化日期
latest_data['date'] = latest_data['date'].strftime('%Y-%m-%d')
previous_data['date'] = previous_data['date'].strftime('%Y-%m-%d')


# 指标卡片样式
def metric_card(title, value, delta=None, unit="", is_percent=False, color="primary"):
    if is_percent:
        value_str = f"{value:.2f}%"
        if delta is not None:
            delta_str = f"{delta:.2f}%"
    else:
        if value >= 1e6:
            value_str = f"{value / 1e6:.2f}M"
        elif value >= 1e3:
            value_str = f"{value / 1e3:.2f}K"
        else:
            value_str = f"{value}"

        if delta is not None:
            if delta >= 1e6:
                delta_str = f"{delta / 1e6:.2f}M"
            elif delta >= 1e3:
                delta_str = f"{delta / 1e3:.2f}K"
            else:
                delta_str = f"{delta}"

    if delta is not None:
        delta_color = "normal"
        if delta > 0:
            delta_color = "positive"
        elif delta < 0:
            delta_color = "negative"

        st.metric(
            label=title,
            value=value_str,
            delta=delta_str if delta is not None else None,
            delta_color=delta_color
        )
    else:
        st.markdown(f"""
            <div class="metric-card" style="background-color: #f0f2f6; border-radius: 10px; padding: 1rem; margin-bottom: 1rem;">
                <div style="font-size: 0.875rem; color: #6b7280; margin-bottom: 0.25rem;">{title}</div>
                <div style="font-size: 1.5rem; font-weight: bold; color: {'#165DFF' if color == 'primary' else '#333'}">{value_str}</div>
            </div>
        """, unsafe_allow_html=True)


# 主要指标展示
st.header("关键指标概览")
col1, col2, col3 = st.columns(3)
with col1:
    metric_card(
        "分保费收入增长率",
        latest_data['reinsurance_growth_rate'],
        latest_data['reinsurance_growth_rate'] - previous_data['reinsurance_growth_rate'],
        is_percent=True
    )
    metric_card(
        "分保费收入市场份额",
        latest_data['market_share'],
        latest_data['market_share'] - previous_data['market_share'],
        is_percent=True
    )
with col2:
    metric_card(
        "自留保费增长率",
        latest_data['net_premium_growth_rate'],
        latest_data['net_premium_growth_rate'] - previous_data['net_premium_growth_rate'],
        is_percent=True
    )
    metric_card(
        "分保费收入增量市场份额",
        latest_data['incremental_market_share'],
        latest_data['incremental_market_share'] - previous_data['incremental_market_share'],
        is_percent=True
    )
with col3:
    metric_card(
        "首年保费与保费收入比",
        latest_data['first_year_premium_ratio'] * 100,
        (latest_data['first_year_premium_ratio'] - previous_data['first_year_premium_ratio']) * 100,
        is_percent=True
    )
    metric_card(
        "标准保费增长率",
        latest_data['standard_premium_growth_rate'],
        latest_data['standard_premium_growth_rate'] - previous_data['standard_premium_growth_rate'],
        is_percent=True
    )

# 图表区域
st.header("趋势分析")

# 保费收入相关指标
fig1, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 5))

# 分保费收入与自留保费趋势
ax1.plot(df['date'], df['reinsurance_premium'], 'b-', label='分保费收入')
ax1.plot(df['date'], df['net_premium'], 'g-', label='自留保费')
ax1.set_title('分保费收入 vs 自留保费')
ax1.set_xlabel('日期')
ax1.set_ylabel('金额 (万元)')
ax1.legend()
ax1.grid(True)

# 增长率趋势
ax2.plot(df['date'], df['reinsurance_growth_rate'], 'b-', label='分保费收入增长率')
ax2.plot(df['date'], df['net_premium_growth_rate'], 'g-', label='自留保费增长率')
ax2.plot(df['date'], df['standard_premium_growth_rate'], 'r-', label='标准保费增长率')
ax2.set_title('保费增长率趋势')
ax2.set_xlabel('日期')
ax2.set_ylabel('增长率 (%)')
ax2.legend()
ax2.grid(True)

plt.tight_layout()
st.pyplot(fig1)

# 市场份额与其他指标
fig2, (ax3, ax4) = plt.subplots(1, 2, figsize=(15, 5))

# 市场份额趋势
ax3.plot(df['date'], df['market_share'], 'b-', label='市场份额')
ax3.plot(df['date'], df['incremental_market_share'], 'g-', label='增量市场份额')
ax3.set_title('市场份额趋势')
ax3.set_xlabel('日期')
ax3.set_ylabel('份额 (%)')
ax3.legend()
ax3.grid(True)

# 首年保费占比与人均保费
ax4.plot(df['date'], df['first_year_premium_ratio'] * 100, 'b-', label='首年保费占比')
ax4.plot(df['date'], df['premium_per_agent'], 'g-', label='人均保费')
ax4.set_title('首年保费占比 vs 人均保费')
ax4.set_xlabel('日期')
ax4.set_ylabel('首年保费占比 (%) / 人均保费 (元)')
ax4.legend()
ax4.grid(True)

plt.tight_layout()
st.pyplot(fig2)

# 最后一个指标
st.header("财务健康指标")
fig3, ax5 = plt.subplots(figsize=(15, 5))

# 自留保费占净资产比
ax5.plot(df['date'], df['net_premium_to_assets_ratio'], 'b-')
ax5.set_title('自留保费占净资产比')
ax5.set_xlabel('日期')
ax5.set_ylabel('比例 (%)')
ax5.grid(True)

plt.tight_layout()
st.pyplot(fig3)

# 数据表格
st.header("详细数据")
df_display = df.copy()
df_display['date'] = df_display['date'].dt.strftime('%Y-%m-%d')

# 格式化百分比列
percent_cols = [
    'reinsurance_growth_rate', 'net_premium_growth_rate',
    'first_year_premium_ratio', 'standard_premium_growth_rate',
    'net_premium_to_assets_ratio', 'market_share', 'incremental_market_share'
]

for col in percent_cols:
    if 'ratio' in col or 'share' in col:
        df_display[col] = df_display[col].apply(lambda x: f"{x * 100:.2f}%")
    else:
        df_display[col] = df_display[col].apply(lambda x: f"{x:.2f}%")

# 格式化金额列
amount_cols = [
    'premium_income', 'reinsurance_premium', 'net_premium',
    'first_year_premium', 'standard_premium', 'net_assets', 'premium_per_agent'
]

for col in amount_cols:
    if col == 'premium_per_agent':
        df_display[col] = df_display[col].apply(lambda x: f"{x:.0f}元")
    else:
        df_display[col] = df_display[col].apply(lambda x: f"{x / 10000:.2f}万元")

# 重新排序列
display_order = [
    'date', 'premium_income', 'reinsurance_premium', 'net_premium',
    'first_year_premium', 'standard_premium', 'num_agents', 'net_assets',
    'market_share', 'incremental_market_share', 'reinsurance_growth_rate',
    'net_premium_growth_rate', 'first_year_premium_ratio', 'standard_premium_growth_rate',
    'premium_per_agent', 'net_premium_to_assets_ratio'
]

df_display = df_display[display_order]

# 重命名列
new_names = {
    'date': '日期',
    'premium_income': '保费收入',
    'reinsurance_premium': '分保费收入',
    'net_premium': '自留保费',
    'first_year_premium': '首年保费',
    'standard_premium': '标准保费',
    'num_agents': '代理人数量',
    'net_assets': '净资产',
    'market_share': '分保费收入市场份额',
    'incremental_market_share': '分保费收入增量市场份额',
    'reinsurance_growth_rate': '分保费收入增长率',
    'net_premium_growth_rate': '自留保费增长率',
    'first_year_premium_ratio': '首年保费与保费收入比',
    'standard_premium_growth_rate': '标准保费增长率',
    'premium_per_agent': '人均保费',
    'net_premium_to_assets_ratio': '自留保费占净资产比'
}

df_display = df_display.rename(columns=new_names)

# 显示表格
st.dataframe(df_display)

# 页脚
st.markdown("""
<style>
footer {
    visibility: hidden;
}
</style>
""", unsafe_allow_html=True)